package com.orange.off.cloud.cloudoff.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.RegisteredEvent;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.ProgressDlgUtil;
import com.orange.off.cloud.cloudoff.utils.SPUtil;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;
import com.orange.off.cloud.cloudoff.views.CountDownButtonHelper;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 登录------忘记密码
 *
 * @author smile
 */
public class ForgetPwdFragment extends Fragment {


    @Bind(R.id.rt_changepwdBack)
    RelativeLayout rtChangepwdBack;
    @Bind(R.id.changepwd_code)
    EditText changepwdCode;
    @Bind(R.id.changepwd_code_btn)
    Button changepwdCodeBtn;
    @Bind(R.id.changepwd_pwd)
    EditText changepwdPwd;
    @Bind(R.id.changepwd_submit_button)
    Button changepwdSubmitButton;
    @Bind(R.id.tv_changepwdTitle)
    TextView tvChangepwdTitle;
    @Bind(R.id.changepwd_tel)
    EditText changepwdTel;
    private CountDownButtonHelper helper;
    private Boolean isTimer = false;
    private String code = "";

    public static ForgetPwdFragment newInstance() {
        ForgetPwdFragment fragment = new ForgetPwdFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.changepwdfragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    private void initViews() {
        //修改标题名：
        tvChangepwdTitle.setText("忘记密码");
        String phone = (String) SPUtil.get(getActivity(), "username", "");
        changepwdTel.setText(phone);

    }


    @OnClick({R.id.rt_changepwdBack, R.id.changepwd_code_btn, R.id.changepwd_submit_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rt_changepwdBack:
                //返回：
                if (isTimer) {
                    helper.close();
                }
                getActivity().finish();
                break;
            case R.id.changepwd_code_btn:
                //获取验证码：
                changepwdCodeBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.registered_code_down));
                helper = new CountDownButtonHelper(changepwdCodeBtn, "重新获取", 60, 1);
                helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() {

                    @Override
                    public void finish() {
                        changepwdCodeBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.registered_code_on));
                    }
                });
                helper.start();
                isTimer = true;
                getCode();
                break;
            case R.id.changepwd_submit_button:
                //保存提交：
                final String phone = changepwdTel.getText().toString().trim();
                final String password = changepwdPwd.getText().toString().trim();
                String VerificationCode = changepwdCode.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.show(getActivity(), "手机号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    ToastUtils.show(getActivity(), "密码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(VerificationCode)) {
                    ToastUtils.show(getActivity(), "验证码不能为空");
                    return;
                }
                if (!code.equals(VerificationCode)) {
                    ToastUtils.show(getActivity(), "验证码输入错误，请确认短信！");
                    return;
                }
                ProgressDlgUtil.showProgressDlg("密码修改中,请稍后...", getActivity());
                changepwdSubmitButton.setEnabled(false);
                RequestParams params = new RequestParams();
                params.addFormDataPart("aid", MyApplication.aid);
                params.addFormDataPart("account", phone);
                params.addFormDataPart("mima", password);
                params.addFormDataPart("code", VerificationCode);
                //                                Log.d(MyApplication.DEBUG, "UpdatePassword---》" + "account--->" + phone + "----password--->" + password);
                HttpRequest.post(AppUrls.UpdatePassword, params, new BaseHttpRequestCallback<UploadResponse>() {
                    @Override
                    public void onSuccess(UploadResponse uploadResponse) {
                        super.onSuccess(uploadResponse);
                        ProgressDlgUtil.stopProgressDlg();
                        changepwdSubmitButton.setEnabled(true);
                        Log.d(MyApplication.DEBUG, "forget_pwd--success-》" + uploadResponse.toString());

                        if (uploadResponse.getSuccess()) {
                            ToastUtils.show(getActivity(), "密码修改成功，请登录", Toast.LENGTH_SHORT);
                            EventBus.getDefault().post(new RegisteredEvent(phone, password));
                            if (isTimer) {
                                helper.close();
                            }
                            getActivity().finish();
                        } else {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                        }

                    }

                    @Override
                    public void onFailure(int errorCode, String msg) {
                        super.onFailure(errorCode, msg);
                        ProgressDlgUtil.stopProgressDlg();
                        changepwdSubmitButton.setEnabled(true);
                    }

                    @Override
                    public void onProgress(int progress, long networkSpeed, boolean done) {
                    }
                });
                break;
        }
    }

    void getCode() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("phone", changepwdTel.getText().toString().trim());
        Log.d(MyApplication.DEBUG, "getcode---》" + "phone-->" + changepwdTel.getText().toString().trim());
        HttpRequest.post(AppUrls.VerificationCode, params, new BaseHttpRequestCallback<UploadResponse>() {
            @Override
            public void onSuccess(UploadResponse uploadResponse) {
                super.onSuccess(uploadResponse);
                Log.d(MyApplication.DEBUG, "getcode---》" + uploadResponse.toString());

                if (uploadResponse.getSuccess()) {
                    code = uploadResponse.getCode();
                } else {
                    ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onProgress(int progress, long networkSpeed, boolean done) {
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isTimer) {
                helper.close();
            }
            getActivity().finish();
            return true;
        }
        return false;
    }
}
